<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

defined('ANS') or die();

if (!$Vars->var['Filename'] || !$Vars->var['Upload'] || !is_array($Vars->var['uploadfile']) || !$Vars->var['connection'] || !$Vars->var['table'] || !$Vars->var['field'] || !$Vars->var['id']) {
	die(__('Sorry, but the app could not receive all data needed to upload the file'));
}

if (!is_file($Vars->var['uploadfile']['tmp_name'])) {
	die (__('Sorry, but the file uploaded seems not to exists'));
}

$settings = $Config->config['tables'][$Vars->var['connection']][$Vars->var['table']][$Vars->var['field']]->settings[$Vars->var['field']];

if (!$settings) {
	die(__('Sorry, but this field seems not to exists in this table'));
}

$destination_dir = $settings['base_dir'].$settings['subfolder'];

if (!is_dir($destination_dir) || !is_writable($destination_dir)) {
	die (__('Sorry, but the destination folder is not writable'));
}

$newfile = md5(microtime().$Vars->var['uploadfile']['name']).'.'.strtolower(pathinfo($Vars->var['uploadfile']['name'], PATHINFO_EXTENSION));

if (!move_uploaded_file($Vars->var['uploadfile']['tmp_name'], $destination_dir.$newfile)) {
  die(__('Sorry, but the file can not be uploaded to de destination directory'));
}

$ok = $Data->save(array(
	'update' => array(
		'table' => $Vars->var['table'],
		'data' => array(
			$Vars->var['field'] => $settings['subfolder'].$newfile
		),
		'conditions' => array(
			'id' => $Vars->int('id')
		),
		'limit' => 1
	)
));

if ($ok) {
	die(__('File was uploaded successfully'));
} else {
	unlink($destination_dir.$newfile);

	die(__('Sorry, file can be uploaded but the registry does not exists in the table'));
}
?>
